package br.softmarket.visao;

import br.softmarket.modelo.TipoProduto;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

public class FormTipoProduto extends javax.swing.JFrame {

    //lista que servirá como banco (provisório)
    private List<TipoProduto> listTipoProduto;

    public FormTipoProduto() {
        initComponents();
        setResizable(false);
        this.setSize(new Dimension(800, 600));
        this.setTitle("SoftMarket - Tipo Produto");
        this.setLocationRelativeTo(this);
        this.validarCampoCodigo();
        jTable1.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
            }

            @Override
            public void mousePressed(MouseEvent e) {
                int idx = jTable1.getSelectedRow();
                TipoProduto prod = ((Tabela) jTable1.getModel()).getProduto(idx);
                String codigo = String.valueOf(prod.getCodTipoProduto());
                jtfCodigo.setText(codigo);
                jtfDescricao.setText(prod.getDescTipoProduto());
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
        listTipoProduto = new ArrayList<TipoProduto>();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpBotoes = new javax.swing.JPanel();
        jbGravar = new javax.swing.JButton();
        jbExcluir = new javax.swing.JButton();
        jpDescricao = new javax.swing.JPanel();
        jtfDescricao = new javax.swing.JTextField();
        jpCodigo = new javax.swing.JPanel();
        jtfCodigo = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("SoftMarket - Tipo Produto");
        setMinimumSize(new java.awt.Dimension(345, 302));
        setName("frPrincipal"); // NOI18N

        jbGravar.setText("Gravar");
        jbGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbGravarActionPerformed(evt);
            }
        });

        jbExcluir.setText("Excluir");
        jbExcluir.setMaximumSize(new java.awt.Dimension(67, 23));
        jbExcluir.setMinimumSize(new java.awt.Dimension(67, 23));
        jbExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbExcluirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpBotoesLayout = new javax.swing.GroupLayout(jpBotoes);
        jpBotoes.setLayout(jpBotoesLayout);
        jpBotoesLayout.setHorizontalGroup(
            jpBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpBotoesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jbGravar)
                .addGap(18, 18, 18)
                .addComponent(jbExcluir, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE)
                .addContainerGap())
        );
        jpBotoesLayout.setVerticalGroup(
            jpBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpBotoesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbGravar)
                    .addComponent(jbExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jpDescricao.setBorder(javax.swing.BorderFactory.createTitledBorder("Descrição"));

        javax.swing.GroupLayout jpDescricaoLayout = new javax.swing.GroupLayout(jpDescricao);
        jpDescricao.setLayout(jpDescricaoLayout);
        jpDescricaoLayout.setHorizontalGroup(
            jpDescricaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jtfDescricao)
        );
        jpDescricaoLayout.setVerticalGroup(
            jpDescricaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jtfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jpCodigo.setBorder(javax.swing.BorderFactory.createTitledBorder("Código"));

        javax.swing.GroupLayout jpCodigoLayout = new javax.swing.GroupLayout(jpCodigo);
        jpCodigo.setLayout(jpCodigoLayout);
        jpCodigoLayout.setHorizontalGroup(
            jpCodigoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jtfCodigo, javax.swing.GroupLayout.DEFAULT_SIZE, 535, Short.MAX_VALUE)
        );
        jpCodigoLayout.setVerticalGroup(
            jpCodigoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jtfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null}
            },
            new String [] {
                "Código", "Descrição"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jpCodigo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jpDescricao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 454, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jpBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(174, 174, 174))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-555)/2, (screenSize.height-340)/2, 555, 340);
    }// </editor-fold>//GEN-END:initComponents

    private void jbGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbGravarActionPerformed
        TipoProduto tp = new TipoProduto();
        tp.setCodTipoProduto(Integer.parseInt(jtfCodigo.getText()));
        tp.setDescTipoProduto(jtfDescricao.getText());
        listTipoProduto.add(tp);
        JOptionPane.showMessageDialog(null, "Gravado com sucesso!");
        jTable1.setModel(new Tabela(listTipoProduto));
        limparCampos();
    }//GEN-LAST:event_jbGravarActionPerformed

    private void jbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExcluirActionPerformed
        TipoProduto tp = new TipoProduto();
        tp.setCodTipoProduto(Integer.parseInt(jtfCodigo.getText()));
        tp.setDescTipoProduto(jtfDescricao.getText());
        
        listTipoProduto.remove(tp);
        JOptionPane.showMessageDialog(null, "Apagado com sucesso!");
        jTable1.setModel(new Tabela(listTipoProduto));
        limparCampos();
    }//GEN-LAST:event_jbExcluirActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormTipoProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormTipoProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormTipoProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormTipoProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FormTipoProduto().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton jbExcluir;
    private javax.swing.JButton jbGravar;
    private javax.swing.JPanel jpBotoes;
    private javax.swing.JPanel jpCodigo;
    private javax.swing.JPanel jpDescricao;
    private javax.swing.JTextField jtfCodigo;
    private javax.swing.JTextField jtfDescricao;
    // End of variables declaration//GEN-END:variables

    public void limparCampos() {
        jtfCodigo.setText("");
        jtfDescricao.setText("");
    }

    private void validarCampoCodigo() {
        jtfCodigo.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                jtfCodigo.setText(jtfCodigo.getText().replaceAll("[^0-9]", ""));
            }
        });
    }

    public class Tabela extends AbstractTableModel {

        private List<TipoProduto> lista;

        public Tabela(List<TipoProduto> lista) {

            // Instanciando para simular carga do banco de dados,
            // poderia ser passado pronto como parâmetro no construtor.
            this.lista = lista;

        }

        @Override
        public int getRowCount() {
            // um produto por linha.
            return lista.size();
        }

        @Override
        public int getColumnCount() {
            // Somente 2 atributos para Produto.
            return 2;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {

            TipoProduto p = lista.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return p.getCodTipoProduto();
                case 1:
                    return p.getDescTipoProduto();
                default:
                    return "erro";
            }

        }

        @Override
        public String getColumnName(int column) {
            switch (column) {
                case 0:
                    return "Código";
                case 1:
                    return "Descrição";
                default:
                    return "erro";
            }

        }

        public TipoProduto getProduto(int idx) {
            TipoProduto p = lista.get(idx);
            return p;
        }
    }
}